package stardust.core.java.compiler;


import stardust.Stardust;
import stardust.core.java.reflect.MethodReflect;


public class JavaExecuteor
{

  public static Class<?> build(String className, String source) throws ClassNotFoundException
  {
    AbstractClassBuilder builder = ClassBuilderFactory.createClassBuilder();

    builder.add(className, source);
    if (builder.compile())
    {
      return builder.getClassLoader().loadClass(className);
    }
    else
    {
      return null;
    }
  }

  public static void execute(String code) throws Exception
  {
    String tmpClass = "JavaExecuteor" + Stardust.SIGNATURE + System.nanoTime();
    String tmpMethod = tmpClass + "_run()";
    Class<?> clazz = build(tmpClass, "public class " + tmpClass + ""
                                     + "{"
                                     + "	public static void " + tmpMethod + " throws Throwable"
                                     + "{"
                                     + "	" + code
                                     + "}"
                                     + "}");

    MethodReflect.invoke(clazz.newInstance(), tmpClass + "_run");
  }

}
